const {
	Service
} = require("uni-cloud-router");
const {
	redisSet,
	redisGet,
	redisDelete
} = require('common-redis')
const {
	mainSpaceId
} = require('config-space')
module.exports = class RedisService extends(
	Service
) {
	/**
	 * 获取小程序信息缓存
	 */
	async getRedisAppletInfo(appId, fresh) {
		let appletInfo = null
		let key = appId + '-applet-info'
		try{
			let redisRes=await redisGet(key,fresh)
			if(redisRes.code===200){
				appletInfo=redisRes.data
			}else{
				appletInfo = await this.db_getAppletInfo(appId)
				await redisSet(key,appletInfo)
			}
		}catch(e){
			appletInfo = await this.db_getAppletInfo(appId)
		}
		return appletInfo;
	}
	async db_getAppletInfo(appId) {
		const db = uniCloud.database({
		  provider: 'tencent',
		  spaceId: mainSpaceId
		})
		let data = await db.collection("wmz-applet-info").doc(appId).field({
			wechat_id:true,
			alipay_id:true,
			alipay_isv_pid:true,
			create_time:true,
			alipay_version:true,
			wechat_version:true
		}).get()
		data=data.data[0]
		let alipayData = await db.collection("wmz-alipay-authorizerinfo").where({
			app_id:appId
		}).get()
		if(alipayData.data.length>0){
			data.access_token=alipayData.data[0].access_token
			data.alipay_shop_code=alipayData.data[0].alipay_shop_code
			data.alipay_shop_id=alipayData.data[0].alipay_shop_id
		}
		let wechatData = await db.collection("wmz-wechat-authorizerinfo").where({
			app_id:appId
		}).get()
		if(wechatData.data.length>0){
			data.wechat_access_token=wechatData.data[0].access_token
			data.wechat_access_token_updateTime=wechatData.data[0].access_token_updateTime
			data.wechat_authorizer_refresh_token=wechatData.data[0].authorizer_refresh_token
			data.mch_id=wechatData.data[0].mch_id
		}
		return data
	}	
	async deleteRedisAppletInfo(appId){
		let key = appId + '-applet-info'
		await redisDelete(key)
	}
};
